import numpy as np
from numpy import *
from matplotlib.pylab import plt

# 创建mat矩阵
a = mat([[1, 2], [3, 4]]); print(a)
# 创建0矩阵
b = np.zeros((3, 4)); print(b)
# 创建1矩阵
c = np.ones((2, 4)); print(c)
# 创建单位矩阵
d = np.eye(5); print(d)
# 创建二维随机矩阵
e = np.random.rand(2, 2); print(e)
# 创建随机整数矩阵
f = np.random.randint(2, 8, size=[2, 5]); print(f)
# 创建对角矩阵
g = np.diag([1, 2, 3]); print(g)
# 创建有序矩阵
h = np.arange(2, 13, 3); print(h)

A = np.array([[1, 2, 9], [7, 5, 6]])
B = np.array([[2, 3, 4], [4, 8, 6], [7, 8, 9]])
C = np.array([[2, 3, 4], [4, 5, 6]])
print(A.shape, B.shape)
# 点乘
print(A * C)
# 矩阵乘
print(A.dot(B)); print(np.dot(A, B))
# 矩阵的逆
print(np.linalg.inv(B))
# 矩阵的转置
print(A.T)

# 按列或行求和
print(A.sum(axis=0)); sum(A,1); sum(A[2:5], 0)
# 按列或行求最大值
print(A.max(axis=0)); A.max(1); max(A[2:5],0)
# 按列或行求最小值
print(A.min(0)); A.min(1); min(A[2:5],1)
# 列或行最大值的索引
print(A.argmax(axis=0)); argmax(A[2:5],1)
# 列或行求最小值的索引
print(A.argmin(0)); print(argmin(A[0:2],0))


# ----------slice切片--------------
A = [
    [1, 2, 3, 4, 6],
    [2, 2, 3, 4, 6],
    [3, 2, 3, 4, 6],
    [4, 2, 3, 4, 6],
    [5, 2, 3, 4, 6]
]
print(A[1:5] )#[2,3,4,5]   (正向，默认步长=1)
print(A[2:] )#[3,4,5,6]     (正向，默认步长=1)
print(A[:5] )#[1,2,3,4,5]   (正向，默认步长=1)
print(A[::2] )#[1,3,5]      (正向，步长=2)
print(A[1:5:2] )#[2,4]       (正向，步长=2)
print(A[-1:-4:-1] )#[6,5,4]  (反向，步长=-1)
print(A[-1::-1] )#[6,5,4,3,2,1]  (反向，步长=-1)
print(A[-2:-5:-2] )#[5,3]      (反向，步长=-2)
print(A[1:-2] )#[2,3,4]      (正向，默认步长=1)
print(A[-1:2:-1] )#[6,5,4]  (反向，步长=-1)

# --------- vstack hstack ---------------
A = [[1, 2, 3], [4, 5, 6]]
B = [[2, 3, 4], [5, 5, 5]]
print(np.vstack((A, B)))    # 列方向合并
print(np.hstack((A, B)))      # 行方向合并

# ---------- c_ r_ --------------
# np.c_ : 按列连接两个矩阵
# np.r_: 按行连接两个矩阵
a = np.array([1, 2, 3]);  b = np.array([4, 5, 6])
print(np.c_[a,b])  #  [[1 4 ], [2 5], [3 6]]
print(np.r_[a,b])  #  [1 2 3 4 5 6]

# -----------广播机制------------
# 若A矩阵任意维度上的长度为1，可复制扩充到B矩阵的相应纬度的长度

a = np.array([[0],[1],[2],[3]]);          # a.shape=(4,1)
b = np.array([1, 2, 3]);                  # b.shape=(1,3)
print(a + b)

a = np.ones([3, 3, 1])  # 多维广播一样的道理
b = np.array([1, 1, 1])
print(a + b)


# -------------np.tile -----------
# np.tile(a,(m,n)): 生成矩阵(m,n)，每个元素为a(可以是矩阵或数)
print(np.tile([4, 3],(3,2))); # np.array([[4,4],[4,4],[4,4]])

# ---------plt.plot(画点线)与plt.scatter(画散点)-----------
x=[1.5,0.8,2.6,1.0,0.6,2.8,1.2,0.9,0.4,1.3,1.2,2.0,1.6,1.8,2.2]
y=[3.1,1.9,4.2,2.3,1.6,4.9,2.8,2.1,1.4,2.4,2.4,3.8,3.0,3.4,4.0]
plt.plot(x, y, 'r.')
plt.show()
plt.scatter(x, y, c='r', marker='x')
plt.show()
